<template>
  <div style="display: inline-block;">
    <el-dialog :visible.sync="dialog" :close-on-click-modal="false" :before-close="cancel" :title="title" append-to-body width="475px" @close="cancel">
      <el-form ref="form" :model="form" :rules="rules" size="small" label-width="88px">
        <el-form-item label="新邮箱" prop="email">
          <el-input v-model="form.email" auto-complete="on"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="text" @click="cancel">取消</el-button>
        <el-button :loading="loading" type="primary" @click="doSubmit">确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import store from '@/store'
import { validEmail } from '@/utils/validate'
import { patchUpdateUser } from '@/api/user'
// import { resetEmail } from '@/api/system/code'
export default {
  props: {
    email: {
      type: String,
      required: true
    },
    userId: {}
  },
  data() {
    const validMail = (rule, value, callback) => {
      if (value === '' || value === null) {
        callback(new Error('新邮箱不能为空'))
      } else if (value === this.email) {
        callback(new Error('新邮箱不能与旧邮箱相同'))
      } else if (validEmail(value)) {
        callback()
      } else {
        callback(new Error('邮箱格式错误'))
      }
    }
    return {
      loading: false, 
      dialog: false, 
      title: '修改邮箱', 
      form: { email: ''},
      codeLoading: false,
      codeData: { type: 'email', value: '' },
      isDisabled: false, time: 60,
      rules: {
        email: [
          { required: true, validator: validMail, trigger: 'blur' }
        ],
      }
    }
  },
  methods: {
    cancel() {
      this.resetForm()
    },
    doSubmit() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          this.loading = true
          patchUpdateUser(this.userId, this.form).then(res => {
            this.loading = false
            this.resetForm()
            this.$notify({
              title: '提示',
              message: '邮箱修改成功',
              type: 'success',
              duration: 1500
            })
            this.$emit('updateInfo')
          }).catch(err => {
            this.loading = false
          })
        } else {
          return false
        }
      })
    },
    resetForm() {
      this.dialog = false
      this.$refs['form'].resetFields()
      this.isDisabled = false
      this.form = { email: ''}
    }
  }
}
</script>

<style scoped>

</style>
